package host.skiree.nettydemo.server.handler;

import host.skiree.nettydemo.message.Message;
import host.skiree.nettydemo.server.dto.impl.UserChannelImpl;
import host.skiree.nettydemo.server.service.MessageHandlerFactory;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;
import io.netty.handler.timeout.IdleState;
import io.netty.handler.timeout.IdleStateEvent;
import lombok.extern.slf4j.Slf4j;

/**
 * @author gcl
 * @date 2022/9/19 9:04
 */
@Slf4j
public class DemoHandler extends ChannelInboundHandlerAdapter {

    @Override
    public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
        Message message = (Message) msg;
        System.out.println(message);
        MessageHandlerFactory.MESSAGE_HANDLER
                .get(message.getMessageType())
                .handleMessage(ctx, message);
    }

    @Override
    public void channelInactive(ChannelHandlerContext ctx) throws Exception {
        UserChannelImpl.USER_CHANNEL_MAP.remove(ctx.channel());
        ctx.channel().close();
    }

    @Override
    public void userEventTriggered(ChannelHandlerContext ctx, Object evt) throws Exception {
        // 处理心跳事件
        if ( evt instanceof IdleStateEvent ){
            IdleStateEvent event = (IdleStateEvent) evt;
            // 触发了读空闲事件
            if (event.state() == IdleState.READER_IDLE) {
                ctx.channel().close();
            }
        }
    }

}
